<?php

class LeftFilters extends CWidget
{

    public $aCategories;
    public $aFilters;

    private $_html = '';
    private $_q = '';

	protected $_aProperties = array();
	protected $_aCounts = array();
	protected $_aFiltered = array();

    public function init()
    {
	    $oCategoryProperty = new CategoryProperty();
	    $oProperties = $oCategoryProperty->getByCategoryId($this->aCategories);
//		print_r($oProperties); exit;

	    $this->_aProperties = array();
	    foreach($oProperties as $oProperty)
		    $this->_aProperties[$oProperty->id] = $oProperty;

	    if(count($this->_aProperties))
	    {
		    $oPropertyValue = new PropertyValue();
		    $oValues = $oPropertyValue->findAllBySql("SELECT * FROM property_value WHERE property_id IN(". implode(', ', array_keys($this->_aProperties)).")");
//		    print_r($oValues); exit;

		    foreach($oValues as $oValue)
		    {
			    if(isset($this->_aProperties[$oValue->property_id]))
				    $this->_aProperties[$oValue->property_id]->values[] = $oValue;
		    }
	    }

	    $oGoods = new Goods();
	    $s = microtime(true);
	    $this->_aCounts = $oGoods->getFilterCounts(
		    $this->_prepareFilter($this->aFilters),
		    ($this->aFilters['category_id'] ? $this->aFilters['category_id'] : null),
            $this->_aProperties
	    );

        $q = !empty($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
        $this->_q = '';
        if($q)
        {
            $aQ = explode('&', $q);
            if($aQ)
            {
                foreach($aQ as $sq)
                {
                    $sq = explode('=', $sq);

                    if(!empty($sq[0]) && !empty($sq[1]) && $sq[0] != 'v')
                    {
                        if($this->_q != '')
                            $this->_q .= '&';
                        $this->_q .= $sq[0]. '=' . $sq[1];
                    }
                }
            }
        }

//	    echo microtime(true)-$s;
//	    print_r($this->_aProperties); exit;
//	    print_r($this->_aCounts); exit;
    }

	protected function _prepareFilter($filters)
	{
		$values = array();
		if(!empty($filters['v']))
		{
//			$filters['v'] = base64_decode($filters['v']);
			$pairs = explode('|', $filters['v']);

			if(count($pairs) > 0)
			{
				foreach($pairs as $pair)
				{
					$values = explode(':', $pair);
					if(!empty($values[0]) && $values[0] > 0 && !empty($values[1]) && $values[1] > 0)
					{
						$this->_aFiltered[$values[1]] = $values[0];
					}
				}
			}
		}

		return $this->_aFiltered;
	}

	protected $_request = '';
	protected function _filterToRequest($value_id, $property_id)
	{
		$tmp = $this->_aFiltered;

		if(isset($this->_aFiltered[$value_id]))
			unset($tmp[$value_id]);
		else
			$tmp[$value_id] = $property_id;

//		print_r($tmp); exit;

		$this->_request = '';
		foreach($tmp as $valId => $propId)
		{
			if($this->_request != '')
			{
				$this->_request .= '|';
			}

			$this->_request .= $propId .':'. $valId;
		}
//echo $this->_request; exit;
//		$this->_request = implode(':', $tmp);

//		$this->_request = base64_encode($this->_request);
		return ($this->_request ? '?v='. $this->_request : '?'). (($this->_request ? '&' : '').$this->_q);
	}

    public function run()
    {
        $this->_bild();
    }

    protected function _bild()
    {
	    if(empty($this->_aProperties))
		    return false;
//print_r($this->_aProperties); exit;
        $this->_html .= '<ul class="properties">';

        foreach($this->_aProperties as $propertyId => $aProperty)
        {
	        $this->_html .= '<li class="selected">
	        <div>'. $aProperty->title .'</div>
	        <ul class="values">';
	        $showCount = true;
//	        print_r($this->_aFiltered);
	        foreach($aProperty['values'] as $aValue)
	        {
		        if(in_array($aValue->id, $this->_aFiltered))
		        {
//			        $showCount = false;
			        break;
		        }
	        }
	        foreach($aProperty['values'] as $aValue)
	        {
//		        print_r($aValue);
//		        echo $aValue->id;
                $showCount = isset($this->_aCounts['property'][$aValue->id]) && $this->_aCounts['property'][$aValue->id] != 0;
	            $this->_html .= '<li><a rel="nofollow" href="'. $this->_filterToRequest($aValue->id, $propertyId) .'" class="'. (!$showCount ? ' disabled' : ''). (isset($this->_aFiltered[$aValue->id]) ? ' selected' : '') .'">'. $aValue->value .' '. ($showCount || !$showCount ? '<i>('. (isset($this->_aCounts['property'][$aValue->id]) ? $this->_aCounts['property'][$aValue->id] : '0') .')</i>' : '') .'</a></li>';
	        }
	        $this->_html .= '</ul></li>';
        }

        $this->_html .= '</ul>';

        return $this->_html;
    }

    public function __toString()
    {
//	    if($this->_html)
//            $this->_html = '<div class="title">Фильтры</div>' . $this->_html;

        return $this->_html;
    }


}